#include "tower.h"
#include "commonFunc.h"

GLuint tower::tex;

using std::list;

tower::tower()
{
    //please NEVER call this
}
tower::tower(int nx, int ny, int nang, int nwidth, int nheight)
{
    //tex = ntex; //GLuint that points to texture
    ang = nang; //Angle
    x = nx; //x coord
    y = ny; //y coord
    width = nwidth; //width
    height = nheight; //height
    target = NULL; //Pointer to target
    range = 200; //Range of towers
    maxfirecd = 1500; //Fire cooldown in units of milliseconds
    //bcost = 1; //base cost modified by difficulty level
    firecd = maxfirecd; //important
}
tower::~tower()
{

}

//Graphics
void tower::draw()
{
    glPushMatrix();
    if (ang == 0)
    {
        glTranslatef(x,y,0);
    } else {
        glTranslatef(x+(width/2),y+(height/2),0);
        glRotatef(ang,0,0,1);
        glTranslatef(-(width/2),-(height/2),0);
    }
    
    glBindTexture(GL_TEXTURE_2D, gettex());
    glBegin(GL_QUADS);
    glTexCoord2i(0,0); //Texture coord
    glVertex3f(0,0,0); //Point coord

    glTexCoord2i(1,0);
    glVertex3f(width,0,0);
    
    glTexCoord2i(1,1);
    glVertex3f(width,height,0);

    glTexCoord2i(0,1);
    glVertex3f(0,height,0);
    glEnd();
    glPopMatrix();

    //This is the line controls
#if towerDebugLines == 1
    if (target != NULL)
    {
        glPushMatrix();

        glDisable(GL_TEXTURE_2D);
        glLineWidth(5);
        glBegin(GL_LINES);
        glVertex3f(x+width/2,y+height/2,0);
        glVertex3f(target->x+target->width/2, target->y+target->height/2,0);
        glEnd();

        glEnable(GL_TEXTURE_2D);
        glPopMatrix();

    }
#endif

    glLoadIdentity();
}

void tower::updateTarget(list<unit*> & l)
{
    //If the tower's current target is out of range, set its target to NULL
    if ((target != NULL) && (getDist(x,y,target->x,target->y) > range))
    {
        target = NULL;
    }
    
    //If it has no target
    if (target == NULL)
    {
        unit* curtar = NULL;
        double curdist = 0;
        for (list<unit*>::iterator it = l.begin(); it != l.end(); it++)
        {
            if (!curtar) //First time in just grab the first on the list
            {
                curtar = *it;
                curdist = getDist(x,y,curtar->x,curtar->y);
            } else { //check to see if this one is closer
                double newdist = getDist(x,y,(*it)->x, (*it)->y);
                if (newdist < curdist)
                {
                    curdist = newdist;
                    curtar = *it;
                }
            }
        }
        //set target to the found closest enemy
        if (curdist <= range)
            target = curtar;
    }
    if (target != NULL)
        ang = getAng(x,y,target->x,target->y)+45;
    
}

GLuint tower::gettex()
{
    return tex;
}
